package xml.xstream.converter;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import xml.xstream.pojo.Bean;
import xml.xstream.pojo.Property;

import java.util.Iterator;

/**
 * @Author longhj
 * @Description TODO
 * @Date 2021/08/07 星期六 15:02
 */
public class BeanConverter implements Converter {
    @Override
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
        Property property = (Property) source;
        if (property.getName() != null) {
            writer.addAttribute("name", property.getName());
        }
        if (property.getValue() != null) {
            writer.addAttribute("value", property.getValue());
        }
        if (property.getRef() != null) {
            writer.addAttribute("ref", property.getRef());
        }
        if (property.getBean() != null) {
            writer.startNode("bean");
            context.convertAnother(property.getBean());
            writer.endNode();
        }
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        Bean bean = new Bean();// 在解析attribute元素时，先创建一个CarAttr对象
        Property property = new Property();
        Iterator attributeNames = reader.getAttributeNames();
        // while (attributeNames.hasNext()) { //遍历打印扫描到的节点
        //     System.out.println(reader.getNodeName());
        //     System.out.println(attributeNames.next().toString());
        // }
        //设置property的属性值
        property.setRef(reader.getAttribute("ref"));
        property.setValue(reader.getAttribute("value"));
        property.setName(reader.getAttribute("name"));

        //判断该节点是否有子节点
        if (reader.hasMoreChildren()) {
            //设置子节点
            property.setBean(bean);
            System.out.println(reader.getNodeName());
            reader.moveDown();
            //子节点赋值
            bean.setClazz(reader.getAttribute("class"));
            bean.setId(reader.getAttribute("id"));
            //节点下移动到子节点 \property\bean
            while (reader.hasMoreChildren()) {
                //子节点下移到子子节点 \property\bean\property
                reader.moveDown();
                //property本节点  bean上一节点（父节点） 转化类型循环
                Property pro = (Property) context.convertAnother(bean, Property.class);
                bean.getProperty().add(pro);
                reader.moveUp();
            }
            reader.moveUp();
        }
        return property;
    }

    @Override
    public boolean canConvert(Class type) {
        return type.equals(Property.class);//转换条件
    }
}
